<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>品牌管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>

    <div style="margin-bottom: 20px">
      <el-button type="primary" round size="medium"
                 @click="$router.push('/sys-admin/product/brand/add-new')">添加品牌</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="100" align="center"></el-table-column>
      <el-table-column prop="logo" label="LOGO" width="100" align="center">
        <template slot-scope="scope">
            <img :src="scope.row.logo" width="40" height="40"/>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="200" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="pinyin" label="拼音" width="250" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="简介" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="keywords" label="关键词列表" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="150" align="center"></el-table-column>
      <el-table-column prop="enable" label="是否启用" width="150" align="center">
        <template slot-scope="scope">
            <el-switch
                v-model="scope.row.enable"
                @change="setEnable(scope.row)"
                active-color="#13ce66"
                inactive-color="#ccc"
                :active-value="1"
                :inactive-value="0">
            </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" circle @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right; margin: 10px auto;">
      <el-pagination
          background
          @current-change="changePage"
          layout="total, prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize">
      </el-pagination>
    </div>

    <el-dialog title="修改相册" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px">

        <el-form-item label="LOGO" prop="logo">
          <el-input v-model="editForm.logo" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="拼音" prop="pinyin">
          <el-input v-model="editForm.pinyin" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="关键词列表" prop="keywords">
          <el-input v-model="editForm.keywords" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdate()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
let localJwt = localStorage.getItem('localJwt');
export default {
  data() {
    return {
      tableData: [],
      total: 0,
      pageSize: 0,
      currentPage: 1,
      dialogFormVisible: false,
      editForm: {
        id: '',
        logo: '',
        name: '',
        pinyin: '',
        description: '',
        keywords: '',
        sort: '',
        enable: ''
      },
      rules: {
        logo: [
          { required: true, message: '请输入LOGO', trigger: 'blur' },
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 2, max: 25, message: '长度在 2 到 25 个字符', trigger: 'blur' }
        ],
        pinyin: [
          { required: true, message: '请输入拼音', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入简介', trigger: 'blur' }
        ],
        keywords: [
          { required: true, message: '请输入关键词', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序序号', trigger: 'blur' },
          { pattern: /^(\d{1}|[1-9]{1}[0-9]{1})$/, message: '排序序号必须是0~99之间的整数', trigger: 'blur' }
        ],
        enable: [
          { required: true, message: '请输入是否禁用', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    setEnable(brand) {
      let enableText = ['禁用', '启用'];
      let url = "http://localhost:8080/brand/" + brand.id;
      let enable = brand.enable;
      if (enable === 1) {
        url += '/1';
      } else {
        url += '/0';
      }
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.$message({
            message: '将【' + brand.name + '】的启用状态修改为【' + enableText[enable] + '】成功！',
            type: 'success'
          });
          this.loadBrandList();
        } else if (jsonResult.state === 404) {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      }).catch(err => {
        let message = '服务器响应错误！';
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
          }
        });
      });
    },
    openEditDialog(brand) {
      let url = "http://localhost:8080/brand/getStandardById?id=" + brand.id;
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        }
      });
    },
    handleUpdate() {
      // 要发送到后端的地址
      let url = "http://localhost:8080/brand/updateInfoById";
      let formData = this.qs.stringify(this.editForm);// 通过qs转换格式（从对象转换为formData）
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url, formData).then((response) => {// 后端那边为updateInfoById(Long id, AlbumUpdateInfoParam albumUpdateInfoParam)
        // 虽然有两个参数，但是前端传过去的 formData 是一整个 id=24&name=xx&description=xx&sort=99
        // Controller应该能自动匹配参数
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.$message({
            message: '修改品牌详情成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadBrandList();
        } else if (jsonResult.state === 404){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadBrandList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    openDeleteConfirm(brand) {
      this.$confirm('此操作将永久删除【' + brand.id + '-' + brand.name + '】相册, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(brand);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleDelete(brand) {
      let url = "http://localhost:8080/brand/delete";
      let formData = 'brandId=' + brand.id;
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url, formData).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.loadBrandList();
        } else if (jsonResult.state === 404){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadBrandList();
            }
          });
        } else if (jsonResult.state === 409){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    changePage(value) {
      this.$router.replace('?page=' + value);
      this.loadBrandList();
    },
    loadBrandList() {
      let page = this.$router.currentRoute.query.page;
      if (!page) {
        page = 1;
      }
      let url = "http://localhost:8080/brand/list?pageNum=" + page;
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.tableData = jsonResult.data.list;
          this.total = jsonResult.data.total;
          this.pageSize = jsonResult.data.pageSize;
          this.currentPage = jsonResult.data.currentPage;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    }
  },
  mounted() {
    this.loadBrandList();
  }
}
</script>
